﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Threading;
using System.Diagnostics;
using System.Windows.Media.Animation;

namespace UCCLIGHT2.Player
{
    public partial class MainPage : UserControl
    {
        DispatcherTimer timer;
        public MainPage()
        {
            InitializeComponent();
            GetMediaInfomation();
            SetEvents();
            SetTimer();
        }

        private void GetMediaInfomation()
        {
            //임시-------------------------------------------------------------------------------------------------------
            mediaElement.Source = new Uri("TestMedia.wmv", UriKind.RelativeOrAbsolute);
            //------------------------------------------------------------------------------------------------------------
        }

        private void SetEvents()
        {          
            this.btnGetSource.Click += new RoutedEventHandler(btnGetSource_Click);
            this.btnPlay.Click += new RoutedEventHandler(btnPlay_Click);
            this.btnStop.Click += new RoutedEventHandler(btnStop_Click);
            this.btnVolume.Click += new RoutedEventHandler(btnVolume_Click);
            this.btnFullScreen.Click += new RoutedEventHandler(btnFullScreen_Click);
            this.mediaElement.MediaOpened += new RoutedEventHandler(mediaElement_MediaOpened);
            this.mediaElement.DownloadProgressChanged += new RoutedEventHandler(mediaElement_DownloadProgressChanged);
            this.seekGrid.MouseLeftButtonDown += new MouseButtonEventHandler(seekGrid_MouseLeftButtonDown);
            this.mediaElement.MediaEnded += new RoutedEventHandler(mediaElement_MediaEnded);
            this.mediaElement.MediaFailed += new EventHandler<ExceptionRoutedEventArgs>(mediaElement_MediaFailed);
            this.mediaInfomationGrid.MouseEnter += new MouseEventHandler(mediaInfomationGrid_MouseEnter);
            this.mediaInfomationGrid.MouseLeave += new MouseEventHandler(mediaInfomationGrid_MouseLeave);
            this.controlGrid.MouseEnter += new MouseEventHandler(controlGrid_MouseEnter);
            this.controlGrid.MouseLeave += new MouseEventHandler(controlGrid_MouseLeave);
            Application.Current.Host.Content.FullScreenChanged += new EventHandler(FullScreenChanged);
        }

        void controlGrid_MouseLeave(object sender, MouseEventArgs e)
        {
            if (Application.Current.Host.Content.IsFullScreen)
            {
                this.ControlGrid_HiddenStoryboard.Begin();
            }
        }

        void controlGrid_MouseEnter(object sender, MouseEventArgs e)
        {
            if (Application.Current.Host.Content.IsFullScreen)
            {
                this.ControlGrid_VisibleStoryboard.Begin();
            }
        }

        

        void mediaInfomationGrid_MouseLeave(object sender, MouseEventArgs e)
        {
            this.mediaInfomation_HiddenStoryboard.Begin();
            this.mediaElement.Margin = new Thickness(0, 30, 0, 0);
        }

        void mediaInfomationGrid_MouseEnter(object sender, MouseEventArgs e)
        {
            this.mediaInfomation_VisibleStoryboard.Begin();
            this.mediaElement.Margin = new Thickness(0, 0, 0, 0);
        }

        double oldWidth { get; set; }
        double oldHeight { get; set; }

        void btnFullScreen_Click(object sender, RoutedEventArgs e)
        {
            //전체화면 전환
            Application.Current.Host.Content.IsFullScreen = true;           
        }

        void FullScreenChanged(object sender, EventArgs e)
        {
            if (Application.Current.Host.Content.IsFullScreen)
            {
                this.oldWidth = this.Width;
                this.oldHeight = this.Height;

                this.Width = double.NaN;
                this.Height = double.NaN;

                mediaElement.VerticalAlignment = System.Windows.VerticalAlignment.Center;
                this.mediaElement.Margin = new Thickness(0, 30, 0, 0);
                this.controlGrid.Opacity = 0;
            }
            else
            {
                this.Width = this.oldWidth;
                this.Height = this.oldHeight;

                mediaElement.VerticalAlignment = System.Windows.VerticalAlignment.Stretch;
                this.mediaElement.Margin = new Thickness(0, 0, 0, 0);
                this.controlGrid.Opacity = 100;
            }
        }

        void mediaElement_MouseEnter(object sender, MouseEventArgs e)
        {
            if (!Application.Current.Host.Content.IsFullScreen)
            {
                if (this.mediaInfomationGrid.Visibility == System.Windows.Visibility.Collapsed)
                {
                    this.mediaInfomationGrid.Visibility = Visibility.Visible;
                    DispatcherTimer infoTimer = new DispatcherTimer();
                    infoTimer.Interval = new TimeSpan(0, 0, 3);
                    infoTimer.Tick += new EventHandler(infoTimer_Tick);
                    infoTimer.Start();
                }
            }            
        }


        void infoTimer_Tick(object sender, EventArgs e)
        {
            DispatcherTimer infoTimer = sender as DispatcherTimer;
            infoTimer.Tick -= new EventHandler(infoTimer_Tick);
            infoTimer.Stop();
            this.mediaInfomationGrid.Visibility = Visibility.Collapsed;
        }

        void btnVolume_Click(object sender, RoutedEventArgs e)
        {
            foreach (object o in volumeGrid.Children)
            {
                Slider temp = o as Slider;
                if ( temp != null)
                {
                    temp.ValueChanged -= new RoutedPropertyChangedEventHandler<double>(slider_ValueChanged);
                    volumeGrid.Children.Remove(temp);   
                    return;
                }
            }
            MakeSilder();           
        }

        private void MakeSilder()
        {
            Slider slider = new Slider();
            slider.Minimum = 0;
            slider.Maximum = 1;
            slider.Height = 100;
            slider.Value = mediaElement.Volume;
            slider.Orientation = Orientation.Vertical;
            slider.VerticalAlignment = System.Windows.VerticalAlignment.Top;
            slider.Margin = new Thickness(0, -100, 0, 0);
            slider.ValueChanged += new RoutedPropertyChangedEventHandler<double>(slider_ValueChanged);
            volumeGrid.Children.Add(slider);         
        }       

        void slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            mediaElement.Volume = e.NewValue;
        }

        void mediaElement_MediaFailed(object sender, ExceptionRoutedEventArgs e)
        {
            MessageBox.Show("미디어 로딩 실패");                
        }

        void mediaElement_MediaEnded(object sender, RoutedEventArgs e)
        {
            InitMedia();
        }

        private void InitMedia()
        {
            timer.Stop();
            btnPlay.Content = "▶";
            
            mediaElement.Position = new TimeSpan(0);
            seekBar.Width = 0;
            this.tbSeek.Text = GetMediaPosition();
        }

        void seekGrid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            seekBar.Width = e.GetPosition(seekGrid).X;

            double selectPercent = seekBar.ActualWidth / seekGrid.ActualWidth;

            mediaElement.Position = new TimeSpan(Convert.ToInt64(mediaElement.NaturalDuration.TimeSpan.Ticks * selectPercent));
        }

        void mediaElement_DownloadProgressChanged(object sender, RoutedEventArgs e)
        {
            this.downloadBar.Width = Convert.ToInt32(seekGrid.ActualWidth * mediaElement.DownloadProgress);
        }

        private void SetTimer()
        {
            timer = new DispatcherTimer();
            timer.Interval = new TimeSpan(10000);
            timer.Tick += new EventHandler(timer_Tick);            
        }

        void timer_Tick(object sender, EventArgs e)
        {
            this.tbSeek.Text = GetMediaPosition();
            this.seekBar.Width = GetSeekbarPosition();            
        }

        private double GetSeekbarPosition()
        {
            double currentPercent = mediaElement.Position.TotalSeconds / mediaElement.NaturalDuration.TimeSpan.TotalSeconds;
            return Convert.ToInt32(seekGrid.ActualWidth * currentPercent);
        }

        void mediaElement_MediaOpened(object sender, RoutedEventArgs e)
        {
            this.tbSeek.Text = GetMediaPosition();
            TogglePlayToPause();
        }    

        private string GetMediaPosition()
        {
            return string.Format("{0}:{1} / {2}:{3}",
                mediaElement.Position.Minutes.ToString("00"),
                mediaElement.Position.Seconds.ToString("00"),
                mediaElement.NaturalDuration.TimeSpan.Minutes.ToString("00"),
                mediaElement.NaturalDuration.TimeSpan.Seconds.ToString("00"));
        }
                
        void btnStop_Click(object sender, RoutedEventArgs e)
        {
            InitMedia();
            mediaElement.Stop();
           
        }

        void btnPlay_Click(object sender, RoutedEventArgs e)
        {
            TogglePlayToPause();            
        }

        private void TogglePlayToPause()
        {
            if (btnPlay.Content.Equals("▶"))
            {
                PlayerStart();                
            }
            else
            {
                PlayerPause();
            }
        }

        private void PlayerPause()
        {
            btnPlay.Content = "▶";
            mediaElement.Pause();
        }

        private void PlayerStart()
        {
            btnPlay.Content = "||";
            mediaElement.Play();
            timer.Start();
        }

        void btnGetSource_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("구현 중 ","퍼가기!",MessageBoxButton.OK);
        }
    }
}
